package main

import (
	"bufio"
	"bytes"
	"golang.org/x/net/http2"
	"io"
	"log"
)

func main() {
	// 创建一个简单的 HTTP/2 服务器
	http2.VerboseLogs = true // 启用日志以便我们可以看到帧的交换情况
	var buf bytes.Buffer
	framer := http2.NewFramer(&buf, &buf)

	// 创建一个简单的 HTTP/2 服务端流
	if err := framer.WriteSettings(); err != nil {
		log.Fatalf("Error writing SETTINGS frame: %v", err)
	}
	if err := framer.WriteSettingsAck(); err != nil {
		log.Fatalf("Error writing SETTINGS ACK frame: %v", err)
	}
	if err := framer.WriteHeaders(http2.HeadersFrameParam{
		StreamID:      1, // 流的ID
		BlockFragment: []byte{},
		EndStream:     false,
		EndHeaders:    true,
	}); err != nil {
		log.Fatalf("Error writing HEADERS frame: %v", err)
	}

	// 发送 RST_STREAM 帧来终止流
	if err := framer.WriteRSTStream(1, http2.ErrCodeCancel); err != nil {
		log.Fatalf("Error writing RST_STREAM frame: %v", err)
	}

	// 模拟读取并输出帧
	bufr := bufio.NewReader(&buf)
	for {
		f, err := http2.ReadFrame(bufr)
		if err == io.EOF {
			break
		} else if err != nil {
			log.Fatalf("Error reading frame: %v", err)
		}
		log.Printf("Received frame: %v", f)
	}
}
